<template>
    <div class="page-wrap" v-loading="loading">
        <div class="header-wrap">
            <div style="background-color: #fff">
                <a-tabs v-model:activeKey="activeKey" @change="handleTabChange" v-if="gradeTabList.length">
                    <a-tab-pane :key="item" :tab="item === 'L9' ? '本期无需求' : item" v-for="item of gradeTabList"></a-tab-pane>
                </a-tabs>
                <HeaderOptionFilter
                    :checkedLine="checkedLine"
                    :checkedPro="checkedPro"
                    :lineOptions="lineOptions"
                    :proOptions="proOptions"
                    @changeLine="handleChangeLine"
                    @changePro="handleChangePro"
                    @showMask="showMask"
                    v-if="activeKey !== 'L9'"
                />
            </div>
        </div>
        <div v-if="activeKey === 'L9'" style="margin-top: 44px">
            <div style="padding: 10px 12px">下列产品本期无需求新增和版本变更</div>
            <div style="background: #fff" v-if="treeData">
                <a-card :title="key" v-for="key of Object.keys(treeData)" :bodyStyle="{ padding: 0 }" :key="key" :bordered="false">
                    <a-collapse accordion expandIconPosition="right">
                        <a-collapse-panel
                            :disabled="!(item.subNodes && item.subNodes.length)"
                            v-for="item of treeData[key]"
                            :key="item.Id"
                            :show-arrow="!!(item.subNodes && item.subNodes.length)"
                        >
                            <template #header>
                                <flexbox>
                                    <a-tag
                                        style="background: rgba(95, 191, 168, 0.14); color: #3ec0a2; border: 1px solid rgba(95, 191, 168, 0.14)"
                                        v-if="item.node.catalogType === '1'"
                                        >{{ $filters.catalogTypeFilter(item.node.catalogType) }}</a-tag
                                    >
                                    <a-tag v-else>{{ $filters.catalogTypeFilter(item.node.catalogType) }}</a-tag>
                                    <span>{{ item.node.catalogName }}</span>
                                </flexbox>
                            </template>
                            <div v-if="item.subNodes && item.subNodes.length">
                                <flexbox v-for="elem of item.subNodes" :key="elem.id">
                                    <a-tag :color="elem.node.catalogType === '1' ? 'green' : ''">{{
                                        $filters.catalogTypeFilter(elem.node.catalogType)
                                    }}</a-tag>
                                    <span>{{ elem.node.catalogName }}</span>
                                </flexbox>
                            </div>
                        </a-collapse-panel>
                    </a-collapse>
                </a-card>
            </div>
        </div>
        <div v-else>
            <div class="mask-wrap" v-if="isShowMask"></div>
            <div style="flex: 1; display: flex; flex-direction: column; overflow-y: hidden; margin-top: 152px">
                <div style="padding-top: 12px; flex: 1; display: flex; flex-direction: column; overflow: hidden">
                    <flexbox justify="center">
                        <a-radio-group v-model:value="showBeijixing" button-style="solid" style="font-size: 14px" @change="handleChangeShowType">
                            <a-radio-button :value="false">产线报告</a-radio-button>
                            <a-radio-button :value="true">北极星<img :src="beijixingImg" style="margin-left: 4px" /></a-radio-button>
                        </a-radio-group>
                    </flexbox>
                    <div style="margin-top: 12px; flex: 1; padding: 0 12px 12px 12px; overflow-y: auto">
                        <CardList
                            :list="list"
                            :searchQuery="searchQuery"
                            :queryArr="queryArr"
                            :reportName="reportName"
                            :reportType="reportType"
                            @getItemData="getItemData"
                            v-if="showBeijixing"
                        />
                        <PreviewList
                            :list="list"
                            :searchQuery="searchQuery"
                            :queryArr="queryArr"
                            :reportName="reportName"
                            :reportType="reportType"
                            v-else
                        />
                    </div>
                    <div style="height: 69px; width: 100vw" v-if="canSave" />
                    <div class="tabbar-wrap" v-if="canSave">
                        <div class="tabbar-cont" @click="handleSave">已阅</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import api from '@/api';
import { deepClone } from '@/utils/util';
import store from '@/store';
import { message } from 'ant-design-vue';
import filters from '@/utils/filter';
import CardList from './components/CardList.vue';
import PreviewList from './components/PreviewList/index.vue';
import HeaderOptionFilter from './HeaderOptionFilter.vue';
import { useRouterApi } from '@/hooks/common/useRouterApi';
import { defineComponent, reactive, toRefs, computed } from 'vue';
const beijixingImg = require('@/assets/svg/北极星.svg');
export default defineComponent({
    components: {
        HeaderOptionFilter,
        CardList,
        PreviewList
    },
    setup() {
        const { router, route, handleBack } = useRouterApi({
            backQuery: {
                path: '/setting'
            }
        });
        const state = reactive<any>({
            checkedLine: 0,
            checkedPro: -1,
            lineOptions: [],
            proOptions: [],
            treeData: [],
            searchQuery: {
                startTime: null,
                endTime: null,
                deliveryMode: null,
                isRequireAnalyse: '否'
            },
            list: [],
            loading: false,
            queryArr: [],
            reportName: '',
            reportType: null,
            headerInfo: {},
            isEmpty: false,
            canShowPreviewItem: {},
            showBeijixing: false,
            activeKey: null,
            isShowMask: false,
            gradeTabList: []
        });
        const canSave = computed(() => {
            const res = state.headerInfo.pushEmpId && state.headerInfo.pushEmpId.indexOf(store.getters.userInfo.employeeDTO.empId) >= 0;
            if (state.headerInfo.readEmpId) {
                return res ? state.headerInfo.readEmpId.indexOf(store.getters.userInfo.employeeDTO.empId) < 0 : false;
            } else {
                return res;
            }
        });
        const handleChangeLine = (val, index) => {
            if (val) {
                state.checkedLine = index;
                getProOptions([state.treeData[index]]);
            }
        };
        const handleChangePro = (val, index) => {
            if (val) {
                state.checkedPro = index;
                getList();
            }
        };
        // 查询所有数据
        const getList = async () => {
            state.list = [];
            if (state.showBeijixing) {
                getBeijixingList();
            } else {
                getPreviewList();
            }
        };
        const getPreviewList = async () => {
            let codeStr = '';
            state.loading = true;
            if (state.checkedPro === 0) {
                state.proOptions.slice(1).forEach((item) => {
                    if (item.subNodes && item.subNodes.length) {
                        const subNodesStr = item.subNodes.map((item) => item.node.catalogCode).join(',');
                        if (codeStr) {
                            codeStr = `${codeStr},${item.catalogCode},${subNodesStr}`;
                        } else {
                            codeStr = `${item.catalogCode},${subNodesStr}`;
                        }
                    } else {
                        if (codeStr) {
                            codeStr = `${codeStr},${item.catalogCode}`;
                        } else {
                            codeStr = `${item.catalogCode}`;
                        }
                    }
                });
            }
            // 不是全部，点击某个产品，1.传自身产品code 2.有子产品的，遍历所有子产品的code
            else {
                const item = state.proOptions[state.checkedPro];
                if (item.subNodes && item.subNodes.length) {
                    const subNodesStr = item.subNodes.map((item) => item.node.catalogCode).join(',');
                    codeStr = `${item.catalogCode},${subNodesStr}`;
                } else {
                    codeStr = item.catalogCode;
                }
            }
            const query = {
                id: route.query.id,
                catalogCode: codeStr
            };
            const { success, moule, errorMsg } = await api.systemReportModel.getSystemReportInfos(query);
            if (success) {
                state.list = [...moule];
                state.canShowPreviewItem = state.list.find(
                    (item) => (item.pmpProductDetailDTO.isSettingReport =
                            1 &&
                            ((state.reportType == 1 && item.pmpProductDetailDTO.isMonth == 1) ||
                                (state.reportType == 2 && item.pmpProductDetailDTO.isQuarter == 1) ||
                                (state.reportType == 3 && item.pmpProductDetailDTO.isHalfYear == 1) ||
                                (state.reportType == 4 && item.pmpProductDetailDTO.isYear == 1)))
                );
            } else {
                message.error(errorMsg);
            }
            state.loading = false;
        };
        const getBeijixingList = async () => {
            state.loading = true;
            if (state.checkedPro === 0) {
                // 如果是全部，参数有两种情况：1 有子产品的传递子产品code拼接成的字符串 2.没有子产品的传递自身的code
                state.queryArr = state.proOptions.slice(1).map((item) => {
                    if (item.subNodes && item.subNodes.length) {
                        const codeStr = item.subNodes.map((item) => item.node.catalogCode).join(',');
                        return {
                            catalogCode: `${item.catalogCode},${codeStr}`,
                            catalogType: '1'
                        };
                    } else {
                        return {
                            catalogCode: item.catalogCode,
                            catalogType: '1'
                        };
                    }
                });
            }
            // 不是全部，点击某个产品，1.传自身产品code 2.有子产品的，遍历所有子产品的code
            else {
                const item = state.proOptions[state.checkedPro];
                if (item.subNodes && item.subNodes.length) {
                    const codeArr = item.subNodes.map((item) => ({
                        catalogCode: item.node.catalogCode,
                        catalogType: '2'
                    }));
                    const codeStr = item.subNodes.map((item) => item.node.catalogCode).join(',');
                    state.queryArr = [
                        {
                            catalogType: '1',
                            catalogCode: `${item.catalogCode},${codeStr}`
                        },
                        ...codeArr
                    ];
                } else {
                    state.queryArr = [
                        {
                            catalogType: '1',
                            catalogCode: item.catalogCode
                        }
                    ];
                }
            }
            let allRequestAArr = [];
            let allRequestBArr = [];
            if (state.proOptions.length) {
                allRequestAArr = state.queryArr.map(
                    async (item) => await api.portalControlModel.getPolarisIndexBoard({
                        ...state.searchQuery,
                        catalogCode: item.catalogCode,
                        catalogType: item.catalogType
                    })
                );
                allRequestBArr = state.queryArr.map(
                    async (item) => await api.portalControlModel.getQualityBoar({
                        ...state.searchQuery,
                        catalogCode: item.catalogCode,
                        catalogType: item.catalogType
                    })
                );
                const list: any = [];
                const resA = await Promise.allSettled(allRequestAArr);
                resA.forEach((item: any) => {
                    const { success, moule } = item.value;
                    if (success) {
                        if (moule.pmpProductDetailDTO.isOutsideSystem === '0') {
                            list.push({
                                isRequireAnalyse: '否',
                                deliveryMode: null,
                                ...moule
                            });
                        } else {
                            list.push(moule);
                        }
                    }
                });
                const resB = await Promise.allSettled(allRequestBArr);
                resB.forEach((item: any, index) => {
                    const { success, moule } = item.value;
                    if (success) {
                        if (moule) {
                            list[index] = {
                                ...list[index],
                                ...moule
                            };
                        }
                    }
                });
                state.loading = false;
                state.list = [...list];
                state.canShowPreviewItem = state.list.find(
                    (item) => (item.pmpProductDetailDTO.isSettingReport =
                            1 &&
                            ((state.reportType == 1 && item.pmpProductDetailDTO.isMonth == 1) ||
                                (state.reportType == 2 && item.pmpProductDetailDTO.isQuarter == 1) ||
                                (state.reportType == 3 && item.pmpProductDetailDTO.isHalfYear == 1) ||
                                (state.reportType == 4 && item.pmpProductDetailDTO.isYear == 1)))
                );
            }
        };
        // 请求某个外采数据
        const getItemData = async ({ index, item }) => {
            const { success, moule } = await api.portalControlModel.getPolarisIndexBoard({
                ...state.searchQuery,
                catalogCode: state.queryArr[index].catalogCode,
                catalogType: state.queryArr[index].catalogType,
                isRequireAnalyse: item.isRequireAnalyse,
                deliveryMode: item.deliveryMode
            });
            if (success) {
                state.list[index] = { ...state.list[index], ...moule, isRequireAnalyse: item.isRequireAnalyse, deliveryMode: item.deliveryMode };
            }
        };

        const getAllProItem = (treeData) => {
            const arr: any = [];
            const getItem = (data) => {
                data.forEach((item) => {
                    if (item.node.catalogType === '0') {
                        if (item.subNodes && item.subNodes.length) {
                            getItem(item.subNodes);
                        }
                    } else {
                        if (item.node.catalogType === '1') {
                            arr.push({
                                id: item.id,
                                ...item.node,
                                subNodes: item.subNodes || []
                            });
                        }
                    }
                });
            };
            getItem(treeData);
            return arr;
        };
        const getProOptions = (treeData) => {
            state.proOptions = getAllProItem(treeData);
            if (state.proOptions.length) {
                state.proOptions.unshift({
                    catalogName: '全部'
                });
                state.checkedPro = 0;
                getList();
            }
        };
        const getSystemStatistics = async () => {
            const { moule, success } = await api.systemReportModel.getSystemStatistics({
                id: route.query.id
            });
            if (success) {
                state.reportName = moule.reportName;
                document.title = state.reportName;
                const { startTime, endTime } = filters.reportTimeRangeFilter(moule.reportName, moule.reportType);
                state.searchQuery.startTime = startTime;
                state.searchQuery.endTime = endTime;
                state.headerInfo = {
                    ...moule
                };
                state.reportType = moule.reportType;
            }
            return success;
        };

        const handleSave = async () => {
            state.loading = true;
            const query = {
                id: route.query.id,
                readEmpId: store.getters.userInfo.employeeDTO.empId
            };
            const { success, errorMsg } = await api.requireReportModel.leaderSave(query);
            if (success) {
                message.success('操作成功');
                getSystemStatistics();
                // router.push({
                //     path: '/energyManage/analysisReport',
                // });
            } else {
                message.error(errorMsg);
            }
            state.loading = false;
        };

        const handleDetail = () => {
            if (state.canShowPreviewItem.pmpProductDetailDTO) {
                router.push({
                    path: '/energyManage/analysisReport/preview',
                    query: {
                        id: route.query.id,
                        catalogCode: state.canShowPreviewItem.pmpProductDetailDTO.catalogCode,
                        startTime: state.searchQuery.startTime,
                        endTime: state.searchQuery.endTime,
                        reportName: state.reportName
                    }
                });
            }
        };

        const handleChangeShowType = () => {
            getList();
        };
        const showMask = (isShowMask) => {
            state.isShowMask = isShowMask;
        };
        const getReportPBIProductGrade = async () => {
            const query = {
                id: route.query.id
            };
            const { success, moule } = await api.requireReportModel.getReportPBIProductGrade(query);
            if (success) {
                if (moule[0]) {
                    state.gradeTabList = [...moule];
                    state.activeKey = moule[0];
                } else {
                    state.gradeTabList = [];
                    state.activeKey = null;
                }
            }
        };
        const handleTabChange = (val) => {
            state.treeData = null;
            getPBITreeData();
        };
        const getPBITreeData = async () => {
            state.isEmpty = false;
            const query = {
                id: route.query.id,
                productGrade: state.activeKey
            };
            const { success, moule } = await api.systemReportModel.getReportPBITreeData(query);
            if (success) {
                if (moule) {
                    if (state.activeKey === 'L9') {
                        const obj = JSON.parse(moule);
                        Object.keys(obj).forEach((key) => {
                            const item = JSON.parse(obj[key]);
                            obj[key] = [];
                            item.forEach((elem) => obj[key].push(...elem.subNodes));
                        });
                        state.treeData = deepClone(obj);
                    } else {
                        state.treeData = JSON.parse(moule);
                        state.lineOptions = state.treeData.map((item) => ({
                            id: item.id,
                            ...item.node
                        }));
                        // 获取产品选项
                        if (state.lineOptions.length) {
                            const res = await getSystemStatistics();
                            if (res) {
                                getProOptions([state.treeData[0]]);
                            }
                        }
                    }
                } else {
                    state.isEmpty = true;
                }
            }
        };
        const initOptions = async () => {
            await getReportPBIProductGrade();
            getPBITreeData();
        };
        initOptions();
        return {
            ...toRefs(state),
            handleChangeLine,
            handleChangePro,
            getItemData,
            handleBack,
            canSave,
            handleSave,
            handleDetail,
            handleChangeShowType,
            showMask,
            handleTabChange,
            beijixingImg
        };
    }
});
</script>

<style scoped lang="less">
.page-wrap {
    height: 100vh;
    background: #f6f6f6;
    transition: all 0.5s ease;
    ::v-deep(.ant-tabs-bar) {
        margin-bottom: 0 !important;
    }
    display: flex;
    flex-direction: column;
    .header-wrap {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 100;
        ::v-deep(.ant-tabs-nav .ant-tabs-tab-active) {
            color: #0176d3 !important;
        }
    }
    .tabbar-wrap {
        width: 100vw;
        padding: 0 12px 8px 12px;
        height: 69px;
        background: #ffffff;
        display: flex;
        justify-content: center;
        align-items: center;
        position: fixed;
        bottom: 0;
        left: 0;
        .tabbar-cont {
            width: 100%;
            height: 45px;
            display: flex;
            justify-content: center;
            align-items: center;
            background: #0478d3;
            color: #fff;
            border-radius: 8px;
            font-size: 16px;
        }
    }
    .mask-wrap {
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: 99;
        height: 100%;
        background-color: #00000073;
    }
    ::v-deep(.ant-collapse) {
        border: none !important;
    }
    ::v-deep(.ant-radio-group) {
        border: 1px solid #0478d3;
        border-radius: 4px;
        .ant-radio-button-wrapper {
            width: 113px;
            text-align: center;
            font-size: 14px;
        }
    }
}
</style>